﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using IInject.Registration.Scanning;

namespace IInject.Web.Mvc
{
	public class IInjectBootstrapper
	{
		public IInjectBootstrapper(IContainer container)
		{
			Container = container;
		}

		public IContainer Container { get; private set; }

		public static void Initialize(IContainer container)
		{
			DependencyResolver.SetResolver(new IInjectDependencyResolver(container));
			container.Set<IControllerActivator, IInjectControllerActivator>();
		}

		public static void MapControllers(IContainer container)
		{
			MapControllers(container, AppDomain.CurrentDomain.GetAssemblies());
		}

		public static void MapControllers(IContainer container, Assembly assembly)
		{
			container.Scan(s =>
			{
				s.Using(ScanningRule.Implements<IController>());
				s.Scan(assembly);
			});
		}

		public static void MapControllers(IContainer container, IEnumerable<Assembly> assemblies)
		{
			foreach (var assembly in assemblies)
			{
				MapControllers(container, assembly);
			}
        }

        public static void MapFilters(IContainer container, bool mapAll = true)
        {
            MapFilters(container, AppDomain.CurrentDomain.GetAssemblies(), mapAll);
        }

        public static void MapFilters(IContainer container, Assembly assembly, bool mapAll = true)
        {
            container.Scan(s =>
            {
                s.Using(ScanningRule.Implements<IActionFilter>(mapAll));
                s.Scan(assembly);
            });
        }

        public static void MapFilters(IContainer container, IEnumerable<Assembly> assemblies, bool mapAll = true)
        {
            foreach (var assembly in assemblies)
            {
                MapFilters(container, assembly, mapAll);
            }
        }

		public void Initialize()
		{
			Initialize(Container);
		}

		public void MapControllers()
		{
			MapControllers(Container, AppDomain.CurrentDomain.GetAssemblies());
		}

		public void MapControllers(Assembly assembly)
		{
			MapControllers(Container, assembly);
		}

		public void MapControllers(IEnumerable<Assembly> assemblies)
		{
			MapControllers(Container, assemblies);
        }

        public void MapFilters(bool mapAll = true)
        {
            MapFilters(Container, AppDomain.CurrentDomain.GetAssemblies(), mapAll);
        }

        public void MapFilters(Assembly assembly, bool mapAll = true)
        {
            MapFilters(Container, assembly, mapAll);
        }

        public void MapFilters(IEnumerable<Assembly> assemblies, bool mapAll = true)
        {
            MapFilters(Container, assemblies, mapAll);
        }
	}
}
